﻿/*
Copyright 2010 Matías Fidemraizer (www.matiasfidemraizer.com).

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/

using System;
using System.Reflection;

namespace Comkarl.Architecture.Patterns.Factory
{
    /// <summary>
    /// Defines the base class for Factory pattern implementations.
    /// </summary>
    /// <remarks>
    /// Factory pattern defines a custom object creation. It can instantiate concrete subclasses.
    /// 
    /// That is an implementation will be switching concrete type creation in order to initialize it in some way. 
    /// </remarks>
    /// <typeparam name="TBase">
    /// The type of base type.
    /// </typeparam>
    public abstract class Factory<TBase> : SinglePatternInstance
    {
        /// <summary>
        /// Creates an instance of specified type.
        /// </summary>
        /// <param name="concreteType">
        /// A concrete type which is a subclass of base type managed by current factory.
        /// </param>
        /// <returns>
        /// A concrete type instance.
        /// </returns>
        public virtual TBase Create<TConcrete>()
            where TConcrete : TBase
        {

            ConstructorInfo concreteConstructor = typeof(TConcrete).GetConstructor
            (
                BindingFlags.Instance | BindingFlags.NonPublic,
                Type.DefaultBinder,
                new Type[] { },
                null
            );

            if (concreteConstructor != null)
            {
                return (TBase)concreteConstructor.Invoke(null);
            }
            else
            {
                throw new FactoryTypeLoadingException<TBase>(this);
            }
        }

        public override void Dispose()
        {
        }

        public override void WarmUp()
        {
            throw new NotSupportedException();
        }
    }
}